import { useState, useEffect, useRef, useCallback, forwardRef, useImperativeHandle } from 'react';
import styles from './AIAvatar.module.css';

export enum ExpressionType {
  NORMAL = 'normal',
  SMILE = 'smile',
  CONFUSED = 'confused',
  LISTENING = 'listening',
  EMBARRASSED = 'embarrassed',
  SLEEPY = 'sleepy',
  CRYING = 'crying',
  HAPPY = 'happy',
  DIZZY = 'dizzy',
  SAD = 'sad',
  COOL = 'cool',
  FOOLISH = 'foolish',
  CRY = 'cry',
  ANGRY = 'angry',
}

export enum ColorType {
  DEFAULT = 'default',
  GREEN = 'green',
  RED = 'red',
  BLUE = 'blue',
  PURPLE = 'purple',
  ORANGE = 'orange',
  PINK = 'pink',
  GRADIENT_GREEN = 'gradient-green',
  GRADIENT_BLUE = 'gradient-blue',
  GRADIENT_PURPLE = 'gradient-purple',
  GRADIENT_SUNSET = 'gradient-sunset',
  CUSTOM = 'custom',
  AUTO = 'auto'
}

export interface AIAvatarRef {
  switchExpression: () => void;
}

interface AIAvatarProps {
  size?: number;
  expression?: ExpressionType;
  autoExpression?: boolean;
  className?: string;
  colorType?: ColorType;
  customColor?: string;
  customGradient?: {
    from: string;
    to: string;
    direction?: string;
  };
  onClick?: () => void;
}

const AIAvatar = forwardRef<AIAvatarRef, AIAvatarProps>(({ 
  size = 180, 
  expression = ExpressionType.NORMAL,
  autoExpression = true,
  className = '',
  colorType = ColorType.DEFAULT,
  customColor,
  customGradient,
  onClick
}, ref) => {
  const [currentExpression, setCurrentExpression] = useState<ExpressionType>(expression);
  const [currentColorType, setCurrentColorType] = useState<ColorType>(colorType);
  const [isShaking, setIsShaking] = useState<boolean>(false);
  const currentIndexRef = useRef<number>(0);

  // 表情列表（统一的顺序表情）
  const expressions: ExpressionType[] = [
    ExpressionType.NORMAL,
    ExpressionType.SMILE,
    ExpressionType.CONFUSED,
    ExpressionType.LISTENING,
    ExpressionType.EMBARRASSED,
    ExpressionType.SLEEPY,
    ExpressionType.CRYING,
    ExpressionType.HAPPY,
    ExpressionType.DIZZY,
    ExpressionType.SAD,
    ExpressionType.COOL,
    ExpressionType.FOOLISH,
    ExpressionType.CRY,
    ExpressionType.ANGRY
  ];

  // 切换到下一个表情的统一函数
  const switchToNextExpression = useCallback(() => {
    currentIndexRef.current = (currentIndexRef.current + 1) % expressions.length;
    const nextExpression = expressions[currentIndexRef.current];
    setCurrentExpression(nextExpression);
  }, []);

  // 暴露给父组件的方法
  useImperativeHandle(ref, () => ({
    switchExpression: switchToNextExpression
  }), [switchToNextExpression]);

  // 表情控制逻辑
  useEffect(() => {
    if (!autoExpression) {
      setCurrentExpression(expression);
      return;
    }

    // 每8秒按顺序切换表情
    const interval = setInterval(() => {
      currentIndexRef.current = (currentIndexRef.current + 1) % expressions.length;
      const nextExpression = expressions[currentIndexRef.current];
      setCurrentExpression(nextExpression);
    }, 8000);

    return () => clearInterval(interval);
  }, [autoExpression, expression]);

  // 自动颜色切换逻辑
  useEffect(() => {
    if (colorType !== ColorType.AUTO) {
      setCurrentColorType(colorType);
      return;
    }

    // 可用于自动切换的颜色类型（排除AUTO和CUSTOM）
    const availableColors: ColorType[] = [
      ColorType.DEFAULT,
      ColorType.GREEN,
      ColorType.RED,
      ColorType.BLUE,
      ColorType.PURPLE,
      ColorType.ORANGE,
      ColorType.PINK,
      ColorType.GRADIENT_GREEN,
      ColorType.GRADIENT_BLUE,
      ColorType.GRADIENT_PURPLE,
      ColorType.GRADIENT_SUNSET
    ];

    // 随机选择颜色
    const colorCycle = () => {
      const randomColor = availableColors[Math.floor(Math.random() * availableColors.length)];
      setCurrentColorType(randomColor);
    };

    // 每7秒随机切换颜色
    const colorInterval = setInterval(colorCycle, 8000);
    return () => clearInterval(colorInterval);
  }, [colorType]);

  // 点击处理函数
  const handleClick = () => {
    // 只调用外部传入的点击事件
    onClick?.();
  };

  // 防抖处理的摇晃效果
  const handleMouseEnter = () => {
    if (isShaking) return; // 防抖：如果正在摇晃则忽略
    
    setIsShaking(true);
    setTimeout(() => {
      setIsShaking(false);
    }, 400); // 摇晃动画持续400ms
  };

  // 获取背景颜色配置
  const getBackgroundColor = () => {
    switch (currentColorType) {
      case ColorType.GREEN:
        return '#10B981';
      case ColorType.RED:
        return '#EF4444';
      case ColorType.BLUE:
        return '#3B82F6';
      case ColorType.PURPLE:
        return '#8B5CF6';
      case ColorType.ORANGE:
        return '#F97316';
      case ColorType.PINK:
        return '#EC4899';
      case ColorType.GRADIENT_GREEN:
        return 'url(#gradient-green)';
      case ColorType.GRADIENT_BLUE:
        return 'url(#gradient-blue)';
      case ColorType.GRADIENT_PURPLE:
        return 'url(#gradient-purple)';
      case ColorType.GRADIENT_SUNSET:
        return 'url(#gradient-sunset)';
      case ColorType.CUSTOM:
        if (customGradient) {
          return 'url(#custom-gradient)';
        }
        return customColor || '#07C160';
      case ColorType.DEFAULT:
      default:
        return '#07C160';
    }
  };

  // 获取光晕颜色配置
  const getGlowColor = () => {
    switch (currentColorType) {
      case ColorType.GREEN:
        return '#10B981';
      case ColorType.RED:
        return '#EF4444';
      case ColorType.BLUE:
        return '#3B82F6';
      case ColorType.PURPLE:
        return '#8B5CF6';
      case ColorType.ORANGE:
        return '#F97316';
      case ColorType.PINK:
        return '#EC4899';
      case ColorType.GRADIENT_GREEN:
        return '#10B981';
      case ColorType.GRADIENT_BLUE:
        return '#3B82F6';
      case ColorType.GRADIENT_PURPLE:
        return '#8B5CF6';
      case ColorType.GRADIENT_SUNSET:
        return '#F97316';
      case ColorType.CUSTOM:
        return customColor || '#07C160';
      case ColorType.DEFAULT:
      default:
        return '#07C160';
    }
  };

  // 渲染渐变定义
  const renderGradients = () => {
    return (
      <defs>
        <linearGradient id="gradient-green" x1="0%" y1="0%" x2="100%" y2="100%">
          <stop offset="0%" stopColor="#10B981" />
          <stop offset="100%" stopColor="#059669" />
        </linearGradient>
        <linearGradient id="gradient-blue" x1="0%" y1="0%" x2="100%" y2="100%">
          <stop offset="0%" stopColor="#3B82F6" />
          <stop offset="100%" stopColor="#1D4ED8" />
        </linearGradient>
        <linearGradient id="gradient-purple" x1="0%" y1="0%" x2="100%" y2="100%">
          <stop offset="0%" stopColor="#8B5CF6" />
          <stop offset="100%" stopColor="#7C3AED" />
        </linearGradient>
        <linearGradient id="gradient-sunset" x1="0%" y1="0%" x2="100%" y2="100%">
          <stop offset="0%" stopColor="#F97316" />
          <stop offset="50%" stopColor="#EF4444" />
          <stop offset="100%" stopColor="#EC4899" />
        </linearGradient>
        {customGradient && (
          <linearGradient 
            id="custom-gradient" 
            x1="0%" y1="0%" 
            x2={customGradient.direction === 'horizontal' ? '100%' : '0%'} 
            y2={customGradient.direction === 'horizontal' ? '0%' : '100%'}
          >
            <stop offset="0%" stopColor={customGradient.from} />
            <stop offset="100%" stopColor={customGradient.to} />
          </linearGradient>
        )}
      </defs>
    );
  };

  const renderEyes = () => {
    switch (currentExpression) {
      case ExpressionType.SMILE:
        return (
          <>
            {/* 微笑的弯眼睛（更明显的弧度） */}
            <path d="M7.8 10.8c0.8-0.6 1.6-0.6 2.4 0" stroke="white" strokeWidth="0.8" fill="none" strokeLinecap="round"/>
            <path d="M13.8 10.8c0.8-0.6 1.6-0.6 2.4 0" stroke="white" strokeWidth="0.8" fill="none" strokeLinecap="round"/>
          </>
        );
      case ExpressionType.CONFUSED:
        return (
          <>
            {/* 困惑的眼睛（一个大圆一个小点） */}
            <circle cx="9.5" cy="10.5" r="1.2" fill="white"/>
            <circle cx="14.5" cy="10.5" r="0.4" fill="white"/>
          </>
        );
      case ExpressionType.EMBARRASSED:
        return (
          <>
            {/* 害羞的眼睛（更长的竖直矩形，圆角端点） */}
            <rect x="8.8" y="8.8" width="1.4" height="3.4" rx="0.7" ry="0.7" fill="white"/>
            <rect x="13.8" y="8.8" width="1.4" height="3.4" rx="0.7" ry="0.7" fill="white"/>
          </>
        );
      case ExpressionType.SLEEPY:
        return (
          <>
            {/* 困倦的眼睛（横向条） */}
            <rect x="8.2" y="10.2" width="2.6" height="0.6" rx="0.3" ry="0.3" fill="white"/>
            <rect x="13.2" y="10.2" width="2.6" height="0.6" rx="0.3" ry="0.3" fill="white"/>
          </>
        );
      case ExpressionType.CRYING:
        return (
          <>
            {/* 哭泣的眼睛（T形符号） */}
            <g>
              {/* 左眼T形 */}
              <line x1="8.5" y1="9.5" x2="10.5" y2="9.5" stroke="white" strokeWidth="0.8" strokeLinecap="round"/>
              <line x1="9.5" y1="9.5" x2="9.5" y2="11.5" stroke="white" strokeWidth="0.8" strokeLinecap="round"/>
            </g>
            <g>
              {/* 右眼T形 */}
              <line x1="13.5" y1="9.5" x2="15.5" y2="9.5" stroke="white" strokeWidth="0.8" strokeLinecap="round"/>
              <line x1="14.5" y1="9.5" x2="14.5" y2="11.5" stroke="white" strokeWidth="0.8" strokeLinecap="round"/>
            </g>
          </>
        );
      case ExpressionType.HAPPY:
        return (
          <>
            {/* 开心的^^符号 */}
            <path d="M8.4 11.2l0.8-1.2l0.8 1.2" stroke="white" strokeWidth="0.8" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
            <path d="M13.4 11.2l0.8-1.2l0.8 1.2" stroke="white" strokeWidth="0.8" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
          </>
        );
      case ExpressionType.DIZZY:
        return (
          <>
            {/* 晕倒的眼睛（XX符号） */}
            <g>
              {/* 左眼X形 */}
              <line x1="8.5" y1="9.5" x2="10.5" y2="11.5" stroke="white" strokeWidth="0.8" strokeLinecap="round"/>
              <line x1="10.5" y1="9.5" x2="8.5" y2="11.5" stroke="white" strokeWidth="0.8" strokeLinecap="round"/>
            </g>
            <g>
              {/* 右眼X形 */}
              <line x1="13.5" y1="9.5" x2="15.5" y2="11.5" stroke="white" strokeWidth="0.8" strokeLinecap="round"/>
              <line x1="15.5" y1="9.5" x2="13.5" y2="11.5" stroke="white" strokeWidth="0.8" strokeLinecap="round"/>
            </g>
          </>
        );
      case ExpressionType.SAD:
        return (
          <>
            {/* 无语的眼睛（¬ ¬符号） */}
            <path d="M8.2 10.2c0.6 0.2 1.2 0.2 1.8 0" stroke="white" strokeWidth="0.8" fill="none" strokeLinecap="round"/>
            <path d="M13.2 10.2c0.6 0.2 1.2 0.2 1.8 0" stroke="white" strokeWidth="0.8" fill="none" strokeLinecap="round"/>
          </>
        );
      case ExpressionType.COOL:
        return (
          <>
            {/* 正常的眼睛（一个圆眼一个小于号） */}
            <circle cx="9.5" cy="10.5" r="1" fill="white" className={styles.leftEye} />
            <path d="M15.5 9.8l-1.2 0.7l1.2 0.7" stroke="white" strokeWidth="1" fill="none" strokeLinecap="round" strokeLinejoin="round" />
          </>
        );
      case ExpressionType.FOOLISH:
        return (
          <>
            {/* 傻的眼睛（+ +符号） */}
            <g>
              {/* 左眼+形 */}
              <line x1="8.5" y1="10.5" x2="10.5" y2="10.5" stroke="white" strokeWidth="0.8" strokeLinecap="round"/>
              <line x1="9.5" y1="9.5" x2="9.5" y2="11.5" stroke="white" strokeWidth="0.8" strokeLinecap="round"/>
            </g>
            <g>
              {/* 右眼+形 */}
              <line x1="13.5" y1="10.5" x2="15.5" y2="10.5" stroke="white" strokeWidth="0.8" strokeLinecap="round"/>
              <line x1="14.5" y1="9.5" x2="14.5" y2="11.5" stroke="white" strokeWidth="0.8" strokeLinecap="round"/>
            </g>
          </>
        );
      case ExpressionType.CRY:
        return (
          <>
            {/* 哭泣的眼睛（眼泪符号） */}
            <g>
              {/* 左眼眼泪 */}
              <line x1="9.5" y1="9.2" x2="9.5" y2="10.8" stroke="white" strokeWidth="1.2" strokeLinecap="round"/>
              <circle cx="9.5" cy="11.8" r="0.3" fill="white"/>
            </g>
            <g>
              {/* 右眼眼泪 */}
              <line x1="14.5" y1="9.2" x2="14.5" y2="10.8" stroke="white" strokeWidth="1.2" strokeLinecap="round"/>
              <circle cx="14.5" cy="11.8" r="0.3" fill="white"/>
            </g>
          </>
        );
      case ExpressionType.ANGRY:
        return (
          <>
            {/* 生气的眼睛（等边三角形，尖顶向内、居中） */}
            <g>
              {/* 左眼：尖顶向右 */}
              <polygon points="8.5,9.5 8.5,11.5 10.5,10.5" fill="white" />
              {/* 底边在左，尖顶向中心(右) */}
            </g>
            <g>
              {/* 右眼：尖顶向左 */}
              <polygon points="15.5,9.5 15.5,11.5 13.5,10.5" fill="white" />
              {/* 底边在右，尖顶向中心(左) */}
            </g>
          </>
        );
      case ExpressionType.NORMAL:
      case ExpressionType.LISTENING:
      default:
        return (
          <>
            {/* 倾听时的眼睛（两个圆眼睛） */}
            <circle cx="9.5" cy="10.5" r="1" fill="white" />
            <circle cx="14.5" cy="10.5" r="1" fill="white" />
          </>
        );
    }
  };

  const renderMouth = () => {
    return null;
  };

  return (
    <div 
      className={`${styles.aiAvatar} ${className} ${isShaking ? styles.shake : ''}`}
      onMouseEnter={handleMouseEnter}
      onClick={handleClick}
      style={{ cursor: 'pointer' }}
    >
      <svg 
        className={styles.wechatIcon} 
        viewBox="0 0 24 24" 
        fill="none"
        style={{ 
          width: size, 
          height: size,
          filter: `drop-shadow(0 6px 20px ${getGlowColor()}66)`,
          pointerEvents: 'none' // 让点击事件穿透到父div
        }}
      >
        {/* 渐变定义 */}
        {renderGradients()}
        
        {/* 居中的对话气泡 */}
        <path 
          d="M12 4C7.5 4 4 7.1 4 11c0 2.4 1.5 4.5 3.8 5.7L7 20l3.5-2.2c.5.1 1 .2 1.5.2 4.5 0 8-3.1 8-7S16.5 4 12 4z" 
          fill={getBackgroundColor()}
        />
        {/* 动态表情 */}
        {renderEyes()}
        {renderMouth()}
      </svg>
      <div 
        className={styles.avatarShadow}
        style={{
          boxShadow: `0 0 20px ${getGlowColor()}40, 0 0 40px ${getGlowColor()}20`,
          pointerEvents: 'none' // 确保阴影不阻挡点击
        }}
      ></div>
    </div>
  );
});

AIAvatar.displayName = 'AIAvatar';

export default AIAvatar;
